package cn.itcast.bigdata.distributeLock;


import org.I0Itec.zkclient.ZkClient;

//将重复的代码，业务逻辑交给子类去实现
public abstract class ZookeeperAbstractLock implements Lock {
	
	private static final String CONNECT_ADDRESS = "mini1:2181,mini2:2181,mini3:2181";
	
	protected static final String PATH = "/lock";

	protected ZkClient zkClient = new ZkClient(CONNECT_ADDRESS);
	
	protected abstract boolean tryLock();
	
	protected abstract void waitLock();

	
	@Override
	public void getLock() {
		//tryLock  创建zookeeper临时节点，如果创建成功返回true，创建失败返回false
		if (tryLock()){
			System.out.println("获取锁资源");
		}else{
			System.out.println("获取锁资源失败");
			//等待
			waitLock();
			//重新获取
			getLock();
			
		}
	}
	
	@Override
	public void unLock() {
		if (zkClient !=null) {
			zkClient.close();
		}
		System.out.println("释放锁资源");
	}

}
